'use strict'

import Vue from 'vue'
import axios from 'axios'
import qs from 'qs'

axios.interceptors.request.use(config => {
  // loading
  return config
}, error => {
  return Promise.reject(error)
})

axios.interceptors.response.use(response => {
  return response
}, error => {
  return Promise.resolve(error.response)
})

function checkStatus (response) {
  // loading

  // 如果http状态码正常，则直接返回数据
  const code = response.status.toString()
  if (response && (code.startsWith('2'))) {
    return {
      status: 0,
      data: response.data
    }
    // 如果不需要除了data之外的数据，可以直接 return response.data
  }
  // 异常状态下，把错误信息返回去
  return {
    status: 1,
    code: response.data.errcode,
    msg: response.data.errmsg
  }
}

function checkCode (res) {
  // 如果code异常(这里已经包括网络错误，服务器错误，后端抛出的错误)，可以弹出一个错误提示，告诉用户
  if (res.status) {
    if (res.code === 409 || res.code === 400) {
      Vue.$vux.toast.text(res.msg)
    } else if (res.code === 500) {
      Vue.$vux.toast.show({
        type: 'warn',
        text: '网络异常'
      })
    } else {
      console.log(res)
      alert(res.code)
      alert(res.msg)
      Vue.$vux.toast.text('请求失败，请重试')
    }
    return res
  } else {
    return res
  }
}

/**
 * 格式化url占位符
 * eg: http://localhost:8080/yunpan/{id}/aaa/{name}
 * urlFormat(url, {id: '111', name: 'yc'})
 * => http://localhost:8080/yunpan/111/aaa/yc
 *
 * @param url
 * @param param
 * @returns {*}
 */
function _urlFormat (params, url) {
  if (params === undefined || params === null || JSON.stringify(params) === '{}') {
    return url
  }

  let keys = Object.keys(params)
  for (let key of keys) {
    url = url.replace(new RegExp('\\{' + key + '\\}', 'g'), params[key])
  }
  return url
}

export default {
  post (url, params = {}) {
    let data = params.query || {}
    let finalUrl = params.placeholder ? _urlFormat(params.placeholder, url) : url
    return axios({
      method: 'POST',
      url: finalUrl,
      data: qs.stringify(data),
      timeout: 10000,
      headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      }
    }).then(
      (response) => {
        return checkStatus(response)
      }
    ).then(
      (res) => {
        return checkCode(res)
      }
    )
  },
  put (url, params = {}) {
    let data = params.query || {}
    let finalUrl = params.placeholder ? _urlFormat(params.placeholder, url) : url
    return axios({
      method: 'PUT',
      url: finalUrl,
      data: qs.stringify(data),
      timeout: 10000,
      headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      }
    }).then(
      (response) => {
        return checkStatus(response)
      }
    ).then(
      (res) => {
        return checkCode(res)
      }
    )
  },
  get (url, params = {}) {
    let finalUrl = params.placeholder ? _urlFormat(params.placeholder, url) : url
    return axios({
      method: 'GET',
      url: finalUrl,
      // params, // get 请求时带的参数
      timeout: 10000,
      headers: {
        'X-Requested-With': 'XMLHttpRequest'
      }
    }).then(
      (response) => {
        return checkStatus(response)
      }
    ).then(
      (res) => {
        return checkCode(res)
      }
    )
  }
}
